package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.LookDetailsBean;
import com.wnhz.work.yz.molder.EntiretyGoodsMolder2;
import com.wnhz.work.yz.molder.EntiretyMolder1;
import com.wnhz.work.yz.molder.EntiretyShoppingMolder;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.SkillBookPop;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class AddIndustryActivity extends BaseActivity implements View.OnClickListener {
    private RelativeLayout goto_photo;
    private ImageView img;
    private ImageView reduce, ll_add;
    private EditText shopping_number;
    private EditText room_num;
    private EditText remark_ed;
    private LookDetailsBean bean = new LookDetailsBean();
    private EntiretyShoppingMolder molder = new EntiretyShoppingMolder();
    private TextView price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_industry);
        initTitle();
        initData();
        initView();

    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }

    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("加入购物车");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
    }

    private int isYushou;


    private String sku_id, goods_id, total_price, nums22;

    private void initData() {
        isYushou = getIntent().getIntExtra("isYushou", 0);
        if (isYushou != 0) {
            sku_id = getIntent().getStringExtra("sku_id");
            goods_id = getIntent().getStringExtra("goods_id");
            total_price = getIntent().getStringExtra("total_price");
            String budget_id = getIntent().getStringExtra("budget_id");
            molder.setBudget_package_id(budget_id);
            nums22 = getIntent().getStringExtra("nums");
        }

        isYushou = getIntent().getIntExtra("isYushou", 0);
        initPrice = Double.parseDouble(getIntent().getStringExtra("total_price"));
        bean = (LookDetailsBean) getIntent().getSerializableExtra("bean");
        String js = JSON.toJSONString(bean);
        Log.e("----", js);
        DecimalFormat df = new DecimalFormat("######0.00");

        molder.setPrice(df.format(initPrice) + "");
        molder.setPackage_id(bean.getInfo().getPackage_id());
        molder.setSku_id(getIntent().getStringExtra("sku_id"));
        List<EntiretyMolder1> e1s = new ArrayList<>();
        for (int i = 0; i < bean.getInfo().getCate_info().size(); i++) {
            EntiretyMolder1 e1 = new EntiretyMolder1();
            e1.setCate_id(bean.getInfo().getCate_info().get(i).getCate_id());
            List<EntiretyGoodsMolder2> e2s = new ArrayList<>();
            for (int j = 0; j < bean.getInfo().getCate_info().get(i).getData().size(); j++) {
                //
                EntiretyGoodsMolder2 e2 = new EntiretyGoodsMolder2();
                e2.setSku_id(bean.getInfo().getCate_info().get(i).getData().get(j).getSku_id());
                e2.setGoods_nums(bean.getInfo().getCate_info().get(i).getData().get(j).getGoods_nums());
                e2.setGoods_id(bean.getInfo().getCate_info().get(i).getData().get(j).getGoods_id());
                e2s.add(e2);
            }
            e1.setData(e2s);
            e1s.add(e1);
        }
        molder.setData(e1s);
    }

    private int nums;
    private double initPrice;

    private void initView() {
        price = (TextView) findViewById(R.id.price);
        DecimalFormat df = new DecimalFormat("######0.00");
        price.setText(df.format(initPrice) + "");
        nums = 1;
        room_num = (EditText) findViewById(R.id.room_num);
        remark_ed = (EditText) findViewById(R.id.remark_ed);
        goto_photo = (RelativeLayout) findViewById(R.id.goto_photo);
        findViewById(R.id.goto_pay).setOnClickListener(this);
        goto_photo.setOnClickListener(this);
        img = (ImageView) findViewById(R.id.img);
        img.setOnClickListener(this);
        reduce = (ImageView) findViewById(R.id.reduce);
        ll_add = (ImageView) findViewById(R.id.ll_add);
        shopping_number = (EditText) findViewById(R.id.shopping_number);
        shopping_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    nums = Integer.parseInt(s.toString());
                } catch (Exception e) {
                    nums = 1;
                }
                updatePrice();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        reduce.setOnClickListener(this);
        ll_add.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.img:
            case R.id.goto_photo:
                showPopmenu(v);
                break;
            case R.id.ll_add:
                ++nums;
                updatePrice();
                shopping_number.setText(nums + "");
                break;
            case R.id.reduce:
                --nums;
                if (nums == 0) {
                    MyToast("不能再减了");
                    nums = 1;
                }
                updatePrice();
                shopping_number.setText(nums + "");
                break;
            case R.id.goto_pay:
                if (nums22 != null) {
                    if (nums > Integer.parseInt(nums22)) {
                        MyToast("购买数量大于可预购数量");
                        nums = Integer.parseInt(nums22);
                        shopping_number.setText(nums + "");
                        return;
                    }
                }

                gotoPay();
                break;
        }
    }

    private void updatePrice() {
        DecimalFormat df = new DecimalFormat("######0.00");
        int nums = 1;
        try {
            nums = Integer.parseInt(shopping_number.getText().toString());
        } catch (Exception e) {
            nums = 1;
        }
        Double currPrice = nums * initPrice;

        molder.setPrice(df.format(currPrice) + "");
        price.setText(df.format(currPrice) + "");
    }

    private void gotoPay() {
        String url = "";
        if (isYushou != 0) {
            url = Url.BOOKING_BOOKINGPACKAGEADDCART;
        } else {
            url = Url.BATH_PACKAGEADDTOCART;
        }
        String room_number = room_num.getText().toString();
        String intro = remark_ed.getText().toString();
        String nums = shopping_number.getText().toString();


        molder.setIntro(intro);
        molder.setRoom_number(room_number + "");
        molder.setNums(nums);

        String js = JSON.toJSONString(molder);
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("token", MyApplication.getInstance().getUserBean().getToken());
        } catch (Exception e) {
            startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
            return;
        }
        showDialog();
        map.put("json_str", js);
        if (imagePath != null && !imagePath.equals("")) {
            String compressImage = BitnapUtils.compressImage(imagePath, imagePath, 30);
            map.put("cad_img", new File(compressImage));
        }
        Set keys = map.keySet();
        StringBuffer sb = new StringBuffer("");
        if (keys != null) {
            Iterator iterator = keys.iterator();

            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                sb.append("" + key + "--" + value + "\n");
            }
        }
        Log.e("1111", sb.toString());
        XUtil.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:json_str= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        MyToast(info);
                        EventBus.getDefault().post(new Finish1());
                        finish();
                        closeDialog();
                    } else {
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }


    /**
     * ------头像点击
     */
    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    private String imageName;// 原图名称
    private String imagePath;// 原图路径
    private File tempFile;

    /**
     * 图片上传的弹出popwindow
     *
     * @param view
     */
    public void showPopmenu(View view) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        // 显示窗口位置
        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }

    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    startActivityForResult(intent, FROM_CAMERA_CODE);
                    break;
                case R.id.from_album2:

                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    break;

                default:
                    break;
            }
        }
    };

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }


    //得到的图片地址
    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }


        this.imagePath = imagePath;
        x.image().bind(img, "file://" + imagePath);
        img.setVisibility(View.VISIBLE);
        goto_photo.setVisibility(View.GONE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:

                if (null != data) {
                    // 得到图片的全路径
                    Uri uri = data.getData();

                    String imagePath = AlbumImagePath.getPath(this, uri);

                    updateImage(imagePath, uri);

                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {

                    tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    File file = new File(imagePath);

                    if (!file.exists()) {
                        return;
                    }

                    updateImage(imagePath, uri);

                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;


            default:
                break;
        }

    }


}
